package com.example.seckill.application.impl;

import com.example.seckill.application.service.OrderService;
import com.example.seckill.application.service.SecurityService;
import com.example.seckill.application.service.StockService;
import com.example.seckill.applicatoin.exception.ResultCodeMapper;
import com.example.seckill.applicatoin.exception.SystemException;
import com.example.seckill.domain.model.Product;
import com.example.seckill.domain.repository.ProductRepository;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Martin
 */
@Service
public class SeckillService {
    private final ProductRepository productRepository;
    private final OrderService orderService;
    private final StockService stockService;
    private final SecurityService securityService;

    public SeckillService(ProductRepository productRepository, OrderService orderService, StockService stockService, SecurityService securityService) {
        this.productRepository = productRepository;
        this.orderService = orderService;
        this.stockService = stockService;
        this.securityService = securityService;
    }

    /**
     * 秒杀操作
     * @param productId 商品ID
     * @param userId 用户ID
     * @return 是否秒杀成功
     */
    public boolean seckill(Long productId, Long userId) {
        // 检查商品是否存在
        Optional<Product> optionalProduct = productRepository.findById(productId);
        if (!optionalProduct.isPresent()) {
            throw new SystemException("商品不存在！", ResultCodeMapper.UNEXPECTED_ERROR);
        }
        security(productId, userId);
        Product product = optionalProduct.get();
        // 检查商品库存 // 可以放在domain service中
        int stock = stockService.getStock(product);
        if (stock <= 0) {
            throw new SystemException("库存不足",ResultCodeMapper.STOCK_ERROR);
        }
        // 减少商品库存
        stockService.reduceStockV2(product,1);
        // 创建订单
        if (!orderService.createOrder(productId, userId, 1)) {
            // 如果创建订单失败，则增加商品库存
            stockService.increaseStock(productId, 1);
            return false;
        }
        return true;
    }

    private void security(Long productId, Long userId) {
        // 检查用户是否存在
        if (!securityService.checkUser(userId)) {
            throw new SystemException("user不存在！", ResultCodeMapper.UNEXPECTED_ERROR);
        }
        // 检查用户是否有权限访问商品
        if (!securityService.checkAccess(productId, userId)) {
            throw new SystemException("user不存在！", ResultCodeMapper.UNEXPECTED_ERROR);
        }
        // 检查用户下单频率
        if (!securityService.checkFrequency(userId)) {
            throw new SystemException("user不存在！", ResultCodeMapper.UNEXPECTED_ERROR);
        }
    }
}

